import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:lmmi/common/index.dart';

/// 送礼成功弹窗组件
class GiftSuccessDialog extends StatefulWidget {
  final String giftName;
  final String giftPrice;
  final String recipientName;
  final VoidCallback? onClose;

  const GiftSuccessDialog({
    super.key,
    required this.giftName,
    required this.giftPrice,
    required this.recipientName,
    this.onClose,
  });

  @override
  State<GiftSuccessDialog> createState() => _GiftSuccessDialogState();
}

class _GiftSuccessDialogState extends State<GiftSuccessDialog>
    with TickerProviderStateMixin {
  late AnimationController _scaleController;
  late AnimationController _fadeController;
  late AnimationController _confettiController;

  late Animation<double> _scaleAnimation;
  late Animation<double> _fadeAnimation;
  late Animation<double> _confettiAnimation;

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器
    _scaleController = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );

    _fadeController = AnimationController(
      duration: const Duration(milliseconds: 400),
      vsync: this,
    );

    _confettiController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );

    // 初始化动画
    _scaleAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _scaleController, curve: Curves.elasticOut),
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _fadeController, curve: Curves.easeInOut),
    );

    _confettiAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _confettiController, curve: Curves.easeOut),
    );

    // 启动动画序列
    _startAnimations();
  }

  void _startAnimations() async {
    await Future.delayed(const Duration(milliseconds: 100));
    _fadeController.forward();
    await Future.delayed(const Duration(milliseconds: 200));
    _scaleController.forward();
    await Future.delayed(const Duration(milliseconds: 300));
    _confettiController.forward();
  }

  @override
  void dispose() {
    _scaleController.dispose();
    _fadeController.dispose();
    _confettiController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black54,
      child: Center(
        child: AnimatedBuilder(
          animation: Listenable.merge([_scaleAnimation, _fadeAnimation]),
          builder: (context, child) {
            return FadeTransition(
              opacity: _fadeAnimation,
              child: ScaleTransition(
                scale: _scaleAnimation,
                child: Container(
                  width: 300.w,
                  height: 425.h,
                  margin: EdgeInsets.symmetric(horizontal: 20.w),
                  decoration: BoxDecoration(
                    color: const Color(0xFFF3E6D4),
                    borderRadius: BorderRadius.circular(24.r),
                    border: Border.all(
                      color: const Color(0xFFFF8C00),
                      width: 3.w,
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withValues(alpha: 0.2),
                        blurRadius: 20,
                        offset: const Offset(0, 10),
                      ),
                    ],
                  ),
                  child: Stack(
                    children: [
                      // 彩带动画背景
                      AnimatedBuilder(
                        animation: _confettiAnimation,
                        builder: (context, child) {
                          return CustomPaint(
                            size: Size(300.w, 400.h),
                            painter: ConfettiPainter(_confettiAnimation.value),
                          );
                        },
                      ),
                      // 主要内容
                      Padding(
                        padding: EdgeInsets.all(24.w),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            // 成功图标
                            Container(
                              width: 80.w,
                              height: 80.h,
                              decoration: BoxDecoration(
                                color: const Color(0xFFFF8C00),
                                shape: BoxShape.circle,
                                boxShadow: [
                                  BoxShadow(
                                    color: const Color(
                                      0xFFFF8C00,
                                    ).withValues(alpha: 0.3),
                                    blurRadius: 20,
                                    spreadRadius: 5,
                                  ),
                                ],
                              ),
                              child: Icon(
                                Icons.card_giftcard,
                                color: Colors.white,
                                size: 40.sp,
                              ),
                            ),

                            SizedBox(height: 24.h),

                            // 成功标题
                            Text(
                              'Gift Sent Successfully!',
                              style: TextStyle(
                                color: const Color(0xFFFF8C00),
                                fontSize: 24.sp,
                                fontFamily: 'Abhaya Libre SemiBold',
                                fontWeight: FontWeight.w600,
                              ),
                              textAlign: TextAlign.center,
                            ),

                            SizedBox(height: 16.h),

                            // 礼物信息
                            Container(
                              padding: EdgeInsets.all(16.w),
                              decoration: BoxDecoration(
                                color: Colors.white.withValues(alpha: 0.8),
                                borderRadius: BorderRadius.circular(12.r),
                                border: Border.all(
                                  color: const Color(
                                    0xFFFF8C00,
                                  ).withValues(alpha: 0.3),
                                  width: 1.w,
                                ),
                              ),
                              child: Column(
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        'Gift:',
                                        style: TextStyle(
                                          color: const Color(0xFFB26406),
                                          fontSize: 14.sp,
                                          fontFamily: 'PingFang SC',
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                      Text(
                                        widget.giftName,
                                        style: TextStyle(
                                          color: const Color(0xFFFF8C00),
                                          fontSize: 14.sp,
                                          fontFamily: 'Abhaya Libre SemiBold',
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 8.h),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        'Price:',
                                        style: TextStyle(
                                          color: const Color(0xFFB26406),
                                          fontSize: 14.sp,
                                          fontFamily: 'PingFang SC',
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                      Text(
                                        widget.giftPrice,
                                        style: TextStyle(
                                          color: const Color(0xFFFF8C00),
                                          fontSize: 14.sp,
                                          fontFamily: 'Abhaya Libre SemiBold',
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 8.h),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        'To:',
                                        style: TextStyle(
                                          color: const Color(0xFFB26406),
                                          fontSize: 14.sp,
                                          fontFamily: 'PingFang SC',
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                      Text(
                                        widget.recipientName,
                                        style: TextStyle(
                                          color: const Color(0xFFFF8C00),
                                          fontSize: 14.sp,
                                          fontFamily: 'Abhaya Libre SemiBold',
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),

                            SizedBox(height: 24.h),

                            // 关闭按钮
                            GestureDetector(
                              onTap: () {
                                widget.onClose?.call();
                                Navigator.of(context).pop();
                              },
                              child: Container(
                                width: double.infinity,
                                height: 48.h,
                                decoration: BoxDecoration(
                                  color: const Color(0xFFFF8C00),
                                  borderRadius: BorderRadius.circular(24.r),
                                  boxShadow: [
                                    BoxShadow(
                                      color: const Color(
                                        0xFFFF8C00,
                                      ).withValues(alpha: 0.3),
                                      blurRadius: 10,
                                      offset: const Offset(0, 4),
                                    ),
                                  ],
                                ),
                                child: Center(
                                  child: Text(
                                    'OK',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 16.sp,
                                      fontFamily: 'PingFang SC',
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

/// 彩带动画绘制器
class ConfettiPainter extends CustomPainter {
  final double animationValue;

  ConfettiPainter(this.animationValue);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..style = PaintingStyle.fill;

    // 绘制彩带粒子
    for (int i = 0; i < 20; i++) {
      final x =
          (size.width * (i % 5) / 5) + (animationValue * 50 * (i % 3 - 1));
      final y =
          size.height * 0.2 + (animationValue * size.height * 0.6) + (i * 10);

      if (y > size.height) continue;

      paint.color = [
        const Color(0xFFFF8C00),
        const Color(0xFFFFD700),
        const Color(0xFFFF6B6B),
        const Color(0xFF4ECDC4),
        const Color(0xFF45B7D1),
      ][i % 5].withValues(alpha: 1.0 - animationValue);

      canvas.drawCircle(
        Offset(x, y),
        3.0 * (1.0 - animationValue * 0.5),
        paint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

class GiftDialogWidget extends ConsumerStatefulWidget {
  final String? recipientId;
  final String? recipientName;

  const GiftDialogWidget({super.key, this.recipientId, this.recipientName});

  @override
  ConsumerState<GiftDialogWidget> createState() => _GiftDialogWidgetState();
}

class _GiftDialogWidgetState extends ConsumerState<GiftDialogWidget> {
  int selectedGiftIndex = 0; // 默认选择第一个礼物

  // 礼物商品信息
  final List<Map<String, dynamic>> giftProducts = [
    {
      'id': 'com.lmmi.ios.prem.4_99',
      'name': 'Lmmi Pro',
      'price': '\$4.99',
      'image': MyImages.gift1,
      'type': 'non_consumable',
    },
    {
      'id': 'com.lmmi.ios.pri_pic.1x.4_99',
      'name': '1x',
      'price': '\$4.99',
      'image': MyImages.gift2,
      'type': 'consumable',
    },
    {
      'id': 'com.lmmi.ios.pri_pic.5x.14_99',
      'name': '5x',
      'price': '\$14.99',
      'image': MyImages.gift1,
      'type': 'consumable',
    },
    {
      'id': 'com.lmmi.ios.pri_pic.10x.19_99',
      'name': '10x',
      'price': '\$19.99',
      'image': MyImages.gift2,
      'type': 'consumable',
    },
    {
      'id': 'com.lmmi.ios.pri_pic.30x.49_99',
      'name': '30x',
      'price': '\$49.99',
      'image': MyImages.gift1,
      'type': 'consumable',
    },
    {
      'id': 'com.lmmi.ios.pri_vid.1x.6_99',
      'name': '1x',
      'price': '\$6.99',
      'image': MyImages.gift2,
      'type': 'consumable',
    },
    {
      'id': 'com.lmmi.ios.pri_vid.5x.19_99',
      'name': '5x',
      'price': '\$19.99',
      'image': MyImages.gift1,
      'type': 'consumable',
    },
    {
      'id': 'com.lmmi.ios.pri_vid.10x.29_99',
      'name': '10x',
      'price': '\$29.99',
      'image': MyImages.gift2,
      'type': 'consumable',
    },
  ];

  bool _isProcessing = false;

  /// 检查登录状态
  bool _checkLoginStatus() {
    final currentUser = ref.read(currentUserProvider);
    return currentUser != null;
  }

  /// 检查是否是给自己送礼
  bool _isSelfGifting() {
    final currentUser = ref.read(currentUserProvider);
    return currentUser != null && currentUser.id == widget.recipientId;
  }

  /// 显示登录提示
  void _showLoginDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color(0xFFF3E6D4),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.r),
            side: BorderSide(color: const Color(0xFFFF8C00), width: 2.w),
          ),
          title: Text(
            'Login Required',
            style: TextStyle(
              color: const Color(0xFFFF8C00),
              fontSize: 18.sp,
              fontFamily: 'Abhaya Libre SemiBold',
              fontWeight: FontWeight.w600,
            ),
          ),
          content: Text(
            'Please login to send gifts to other users.',
            style: TextStyle(
              color: const Color(0xFFB26406),
              fontSize: 14.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w400,
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text(
                'Cancel',
                style: TextStyle(
                  color: const Color(0xFFB26406),
                  fontSize: 14.sp,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
                Navigator.of(context).pop(); // 关闭礼物弹窗
                context.go('/login'); // 跳转到登录页面
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFFF8C00),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
              child: Text(
                'Login',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  /// 显示本人送礼提示
  void _showSelfGiftingDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color(0xFFF3E6D4),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.r),
            side: BorderSide(color: const Color(0xFFFF8C00), width: 2.w),
          ),
          title: Text(
            'Cannot Send Gift',
            style: TextStyle(
              color: const Color(0xFFFF8C00),
              fontSize: 18.sp,
              fontFamily: 'Abhaya Libre SemiBold',
              fontWeight: FontWeight.w600,
            ),
          ),
          content: Text(
            'You cannot send a gift to yourself. Please select a different recipient.',
            style: TextStyle(
              color: const Color(0xFFB26406),
              fontSize: 14.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w400,
            ),
          ),
          actions: [
            ElevatedButton(
              onPressed: () => Navigator.of(context).pop(),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFFF8C00),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
              child: Text(
                'OK',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  /// 处理礼物购买
  Future<void> _handleGiftPurchase() async {
    // 检查登录状态
    if (!_checkLoginStatus()) {
      _showLoginDialog();
      return;
    }

    // 检查是否有接收者信息
    if (widget.recipientId == null || widget.recipientName == null) {
      _showErrorMessage('Recipient information is missing');
      return;
    }

    // 检查是否是本人
    if (_isSelfGifting()) {
      _showSelfGiftingDialog();
      return;
    }

    if (_isProcessing) return;

    setState(() {
      _isProcessing = true;
    });

    try {
      final selectedGift = giftProducts[selectedGiftIndex];
      final productId = selectedGift['id'] as String;

      // 显示加载对话框
      _showLoadingDialog();

      // 初始化购买管理器
      final purchaseManager = PurchaseManager();
      final initialized = await purchaseManager.initialize();

      if (!initialized) {
        if (mounted) Navigator.of(context).pop(); // 关闭加载对话框
        _showErrorMessage('Payment service is not available');
        return;
      }

      // 发起购买
      final success = await purchaseManager.buyProduct(productId);

      if (mounted) Navigator.of(context).pop(); // 关闭加载对话框

      if (success) {
        // 购买成功，发送礼物消息
        await _sendGiftMessage(selectedGift);

        // 关闭礼物选择弹窗
        if (mounted) Navigator.of(context).pop();

        // 显示成功弹窗
        _showSuccessDialog(selectedGift);
      } else {
        _showErrorMessage('Payment failed. Please try again.');
      }
    } catch (e) {
      if (mounted) Navigator.of(context).pop(); // 关闭加载对话框
      _showErrorMessage('An error occurred: ${e.toString()}');
    } finally {
      if (mounted) {
        setState(() {
          _isProcessing = false;
        });
      }
    }
  }

  /// 发送礼物消息
  Future<void> _sendGiftMessage(Map<String, dynamic> gift) async {
    try {
      final currentUser = ref.read(currentUserProvider);
      if (currentUser == null || widget.recipientId == null) return;

      // 创建简单的文字消息
      final giftMessage =
          '🎁 ${currentUser.username} sent you a gift: ${gift['name']} (${gift['price']})';

      await MessageService.sendMessage(
        senderId: currentUser.id,
        receiverId: widget.recipientId!,
        content: giftMessage,
        type: MessageType.text,
      );
    } catch (e) {
      debugPrint('发送礼物消息失败: $e');
    }
  }

  /// 显示加载对话框
  void _showLoadingDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color(0xFFF3E6D4),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.r),
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF8C00)),
              ),
              SizedBox(height: 16.h),
              Text(
                'Processing payment...',
                style: TextStyle(
                  color: const Color(0xFFB26406),
                  fontSize: 14.sp,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 显示错误消息
  void _showErrorMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.r)),
      ),
    );
  }

  /// 显示成功弹窗
  void _showSuccessDialog(Map<String, dynamic> gift) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return GiftSuccessDialog(
          giftName: gift['name'],
          giftPrice: gift['price'],
          recipientName: widget.recipientName ?? 'Unknown',
          onClose: () {
            // 可以在这里添加额外的回调逻辑
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 400.h,
      decoration: ShapeDecoration(
        color: const Color(0xFFF3E6D4),
        shape: RoundedRectangleBorder(
          side: BorderSide(width: 4.w, color: const Color(0xFFFF8C00)),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(32.r),
            topRight: Radius.circular(32.r),
          ),
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          // 顶部拖拽指示器
          Container(
            padding: EdgeInsets.only(top: 6.h),
            width: 40.w,
            height: 5.h,
            decoration: BoxDecoration(
              color: const Color(0xFFFF8C00).withValues(alpha: 0.3),
              borderRadius: BorderRadius.circular(2.r),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 29.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 54.w,
                  height: 54.h,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(MyImages.giftBg),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                SizedBox(width: 13.w),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 动态价格显示
                    AnimatedSwitcher(
                      duration: const Duration(milliseconds: 300),
                      transitionBuilder:
                          (Widget child, Animation<double> animation) {
                            return ScaleTransition(
                              scale: animation,
                              child: FadeTransition(
                                opacity: animation,
                                child: child,
                              ),
                            );
                          },
                      child: Text(
                        giftProducts[selectedGiftIndex]['price'],
                        key: ValueKey(selectedGiftIndex),
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: const Color(0xFFFF8C00),
                          fontSize: 20.sp,
                          fontFamily: 'Abhaya Libre SemiBold',
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 125.w,
                      child: AnimatedSwitcher(
                        duration: const Duration(milliseconds: 250),
                        child: Text(
                          giftProducts[selectedGiftIndex]['type'] ==
                                  'non_consumable'
                              ? 'Can only be purchased once'
                              : 'Consumable item',
                          key: ValueKey('${selectedGiftIndex}_desc'),
                          style: TextStyle(
                            color: const Color(0x2345204C),
                            fontSize: 12.sp,
                            fontFamily: 'PingFang SC',
                            fontWeight: FontWeight.w300,
                            height: 1.h,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                GestureDetector(
                  onTap: !_isProcessing ? _handleGiftPurchase : null,
                  child: Container(
                    width: 74.w,
                    padding: EdgeInsets.symmetric(
                      horizontal: 8.w,
                      vertical: 2.h,
                    ),
                    decoration: ShapeDecoration(
                      color: _isProcessing
                          ? const Color(0xFFFF8C00).withValues(alpha: 0.6)
                          : const Color(0xFFFF8C00),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.r),
                      ),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      spacing: 10.w,
                      children: [
                        _isProcessing
                            ? SizedBox(
                                width: 12.w,
                                height: 12.h,
                                child: const CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                    Colors.white,
                                  ),
                                ),
                              )
                            : Text(
                                'give away',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 12.sp,
                                  fontFamily: 'PingFang SC',
                                  fontWeight: FontWeight.w400,
                                ),
                              ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 20.h),
          _buildGiftList(),
        ],
      ),
    );
  }

  // 礼物列表
  Widget _buildGiftList() {
    return Container(
      width: 318.w,
      height: 275.h,
      padding: EdgeInsets.symmetric(horizontal: 5.w),
      child: GridView.builder(
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          childAspectRatio: 0.7, // 调整宽高比
          mainAxisSpacing: 8.h,
          crossAxisSpacing: 8.w,
        ),
        itemCount: giftProducts.length,
        itemBuilder: (context, index) {
          final gift = giftProducts[index];
          final isSelected = index == selectedGiftIndex;

          return GestureDetector(
            onTap: () {
              if (!_isProcessing) {
                setState(() {
                  selectedGiftIndex = index;
                });
              }
            },
            child: _buildGiftCard(gift, isSelected),
          );
        },
      ),
    );
  }

  // 构建单个礼物卡片
  Widget _buildGiftCard(Map<String, dynamic> gift, bool isSelected) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        border: isSelected
            ? Border.all(color: const Color(0xFFFF8C00), width: 1.w)
            : null,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 礼物信息部分
          Expanded(
            flex: 3,
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(12.r),
                  topRight: Radius.circular(12.r),
                ),
                border: isSelected
                    ? Border.all(color: Color(0xFFFF8C00), width: 1.w)
                    : Border.all(color: Colors.transparent, width: 1.w),
              ),
              child: Padding(
                padding: EdgeInsets.all(4.w),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    // 礼物图片
                    Expanded(
                      flex: 2,
                      child: Container(
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(gift['image']),
                            fit: BoxFit.contain,
                          ),
                        ),
                      ),
                    ),
                    // 礼物名称
                    Flexible(
                      child: Text(
                        gift['name'],
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: const Color(0xFFB26406),
                          fontSize: 10.sp,
                          fontFamily: 'Abhaya Libre SemiBold',
                          fontWeight: FontWeight.w600,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    // 礼物价格
                    Flexible(
                      child: Text(
                        gift['price'],
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: const Color(0xFFB26406),
                          fontSize: 11.sp,
                          fontFamily: 'Abhaya Libre SemiBold',
                          fontWeight: FontWeight.w600,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          // 送礼按钮
          GestureDetector(
            onTap: isSelected && !_isProcessing ? _handleGiftPurchase : null,
            child: Container(
              height: 22.h,
              decoration: ShapeDecoration(
                color: isSelected
                    ? (_isProcessing
                          ? const Color(0xFFFF8C00).withValues(alpha: 0.6)
                          : const Color(0xFFFF8C00))
                    : const Color(0xFFD09756),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(12.r),
                    bottomRight: Radius.circular(12.r),
                  ),
                ),
              ),
              child: Center(
                child: _isProcessing && isSelected
                    ? SizedBox(
                        width: 12.w,
                        height: 12.h,
                        child: const CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(
                            Colors.white,
                          ),
                        ),
                      )
                    : Text(
                        'give away',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12.sp,
                          fontFamily: 'PingFang SC',
                          fontWeight: FontWeight.w400,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
